<template>
  <div>
    <el-dialog
      :close-on-click-modal="false"
      v-model="visibleDialog"
      :title="props.title"
      width="900px"
      height="600px"
      destroy-on-close
      style="max-height: 800px"
      draggable
      @close="closeDialog"
      append-to-body
    >
      <el-form ref="formRef" :model="formData" :inline="true" :rules="rules">
        <h4 class="mb-[20px] mt-[0px]">基本数据</h4>
        <div class="search-container">
          <el-row>
            <el-col :span="12">
              <el-form-item label="工厂" prop="plantCode" label-width="62">
                <el-input
                  v-if="!props.isReadonly"
                  v-model="formData.plantCode"
                  placeholder="请输入工厂"
                  clearable
                  disabled
                />

                <span v-else>{{ formData.plantCode }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="车间" prop="shopFloorCode" label-width="62">
                <el-input
                  v-if="!props.isReadonly"
                  v-model="formData.shopFloorCode"
                  placeholder="请输入车间编号"
                  clearable
                  disabled
                />

                <span v-else>{{ formData.shopFloorCode }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="班组编号" prop="crewCode">
                <el-input
                  v-if="!props.isReadonly"
                  v-model="formData.crewCode"
                  placeholder="请输入班组编号"
                  clearable
                  disabled
                />

                <span v-else>{{ formData.crewCode }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="班组名称" prop="crewName">
                <el-input
                  v-if="!props.isReadonly"
                  v-model="formData.crewName"
                  placeholder="请输入班组名称"
                  clearable
                  disabled
                />

                <span v-else>{{ formData.crewName }}</span>
              </el-form-item>
            </el-col>
          </el-row>
        </div>
        <h4 class="mb-[20px] mt-[20px]">班组成员</h4>
        <el-card shadow="never" class="table-container">
          <template #header>
            <el-button
              type="success"
              plain
              @click="handleAdd"
              v-if="!props.isReadonly"
            >
              <i-ep-plus />
              新增</el-button
            >
          </template>
          <div class="formTable">
            <el-table
              :data="formData.crewMembers"
              :key="Math.random"
              border
              style="max-height: 200px; overflow: auto"
            >
              <el-table-column
                label="班组成员"
                props="memberName"
                align="center"
                min-width="150"
              >
                <template #default="{ $index, row }">
                  <el-form-item
                    :prop="'crewMembers.' + $index + '.memberList'"
                    label-width="0"
                    :rules="rules.memberRoleId"
                  >
                    <SelectPerson-Member
                      :key="$index"
                      :isMultiple="false"
                      :maxCollapseTags="5"
                      :showSelectPerson="row.memberList"
                      @get-person="
                        (id, object) => getDayPerson(id, object, $index)
                      "
                      :width="'100%'"
                      :disabled="row.memberId != ''"
                    />
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column
                label="工号"
                props="memberEmpNo"
                align="center"
                min-width="120"
              >
                <template #default="{ row }">
                  {{ row.memberEmpNo }}
                </template>
              </el-table-column>
              <el-table-column
                label="性别"
                props="sex"
                align="center"
                min-width="50"
              >
                <template #default="{ row }">
                  {{ useDictionary("SexType", row?.sex || "") }}
                </template>
              </el-table-column>
              <el-table-column
                label="成员角色"
                props="memberRoleName"
                min-width="150"
                align="center"
                style="padding-top: 15px"
              >
                <template #default="{ $index, row }">
                  <el-form-item
                    :prop="'crewMembers.' + $index + '.memberRoleName'"
                    :rules="rules.memberRoleName"
                    label-width="0"
                  >
                    <el-select
                      v-model="row.memberRoleName"
                      placeholder="请选择成员角色"
                      clearable
                      style="width: 100%"
                    >
                      <el-option
                        v-for="item in memberRoleList"
                        :key="item.id"
                        :label="item.memberRoleName"
                        :value="item.memberRoleName"
                      />
                    </el-select>
                  </el-form-item>
                </template>
              </el-table-column>

              <el-table-column
                fixed="right"
                align="center"
                label="操作"
                v-if="!props.isReadonly"
              >
                <template #default="scope">
                  <el-button
                    :disabled="formData.crewMembers.length < 2"
                    type="danger"
                    link
                    @click.stop="handleDelete(scope.$index)"
                    ><i-ep-delete />
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-card>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button
            v-if="!props.isReadonly"
            type="primary"
            :loading="loading"
            @click="handleSubmit"
            >确 定</el-button
          >
          <el-button @click="closeDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import request from "@/utils/request";
import { useDictStoreHook } from "@/store/modules/dictionary";
import { useDictionary } from "../../../../utils/useTable"; // 引入
const dictionaryStore = useDictStoreHook();

defineOptions({
  name: "MESMESCREWMEMBEREDIT",
  inheritAttrs: false,
});

const emit = defineEmits(["reset-table", "change-visible"]);

const props = defineProps({
  visible: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  title: {
    type: String,
    default: () => {
      return "";
    },
  },
  data: {
    type: Object,
    default: () => {
      return {};
    },
  },
  isReadonly: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  crewMembersData: {
    type: Array,
    default: () => {
      return [];
    },
  },
});

/** 弹窗显示 **/
const visibleDialog = ref(false);
watch(
  () => props.visible,
  (newVal: boolean) => {
    visibleDialog.value = newVal;
  }
);

/** formData定义表单数据 */
const formRef = ref(ElForm);
let formData: any = reactive({
  id: "",
  crewCode: "",
  crewName: "",
  crewType: "",
  organizationId: "",
  organizationCode: "",
  plantId: "",
  plantCode: "",
  shopFloorId: "",
  shopFloorCode: "",
  shopFloorName: "",
  version: "",
  remarks: "",
  createTime: "",
  createdUserId: "",
  createdUserName: "",
  lastUpdateTime: "",
  lastUpdatedUserId: "",
  lastUpdatedUserName: "",
  enabled: 1,
  deleted: "",
  userDay: "",
  crewMembers: [
    {
      id: "",
      crewId: "",
      crewCode: "",
      memberId: "",
      memberName: "",
      memberRoleId: "",
      memberRoleName: "",
      deleted: "",
      enabled: 1,
      ids: [],
      organizationCode: "",
      organizationId: "",
      plantCode: "",
      plantId: "",
      remarks: "",
      version: "",
      createTime: "",
      createdUserId: "",
      createdUserName: "",
      lastUpdateTime: "",
      lastUpdatedUserId: "",
      lastUpdatedUserName: "",
      memberList: [],
    },
  ],
  crewEquipments: [],
});

/** rules规则 */
const rules = reactive({
  memberRoleName: [
    {
      required: true,
      message: "请选择角色",
      trigger: "change",
    },
  ],
  memberRoleId: [
    {
      required: true,
      message: "请选择人员",
      trigger: "blur",
    },
  ],
});

/** 删除行 */
const handleDelete = (index: any) => {
  formData.crewMembers.splice(index, 1);
};

const crewMembers: any = {
  id: "",
  crewId: "",
  crewCode: "",
  memberId: "",
  memberName: "",
  memberRoleId: "",
  memberRoleName: "",
  deleted: "",
  enabled: 1,
  ids: [],
  organizationCode: "",
  organizationId: "",
  plantCode: "",
  plantId: "",
  remarks: "",
  version: "",
  createTime: "",
  createdUserId: "",
  createdUserName: "",
  lastUpdateTime: "",
  lastUpdatedUserId: "",
  lastUpdatedUserName: "",
  memberList: [],
};

/** 添加行 */
const handleAdd = () => {
  let sondata = JSON.parse(JSON.stringify(crewMembers));
  formData.crewMembers.push(sondata);
};

/** 编辑时赋值 */
watch(
  () => props.data,
  async (newVal: any) => {
    formData.id = "";
    if (newVal?.id) {
      Object.assign(formData, props.data);

      await request({
        url: "mes/mescrew/getCrewMembers",
        method: "post",
        data: {
          id: newVal.id,
        },
      }).then((res) => {
        // 有id时 发请求获取人员数据并复制
        formData.crewMembers = res.data;
        // 遍历数据 给每个数据添加memberList属性 用于组件回显
        formData.crewMembers.forEach((element, index) => {
          element.memberList = [
            {
              id: element.memberId,
              personName: element.memberName,
              empNo: element.memberEmpNo,
              sex: element.sex,
            },
          ];
        });
      });
    }
  }
);

/** 关闭表单弹窗 */
function closeDialog() {
  visibleDialog.value = false;
  emit("change-visible", false);
  resetForm();
}
const crewMembers1: any = {
  id: "",
  crewId: "",
  crewCode: "",
  memberId: "",
  memberName: "",
  memberRoleId: "",
  memberRoleName: "",
  deleted: "",
  enabled: 1,
  ids: [],
  organizationCode: "",
  organizationId: "",
  plantCode: "",
  plantId: "",
  remarks: "",
  version: "",
  createTime: "",
  createdUserId: "",
  createdUserName: "",
  lastUpdateTime: "",
  lastUpdatedUserId: "",
  lastUpdatedUserName: "",
  memberList: [],
};
/** 重置表单 */
function resetForm() {
  formRef.value.resetFields();
  formData.id = "";
  formData.crewCode = "";
  formData.crewName = "";
  formData.crewType = "";
  formData.organizationId = "";
  formData.organizationCode = "";
  formData.plantId = "";
  formData.plantCode = "";
  formData.shopFloorId = "";
  formData.shopFloorCode = "";
  formData.shopFloorName = "";
  formData.version = "";
  formData.remarks = "";
  formData.createTime = "";
  formData.createdUserId = "";
  formData.createdUserName = "";
  formData.lastUpdateTime = "";
  formData.lastUpdatedUserId = "";
  formData.lastUpdatedUserName = "";
  formData.enabled = 1;
  formData.deleted = "";
  formData.crewMembers = [crewMembers1];
}

const loading = ref(false);

/** 班制保存提交 */
function handleSubmit() {
  formRef.value.validate(async (valid: any) => {
    if (valid) {
      // 根据角色名称添加角色ID
      formData.crewMembers.forEach((element: any) => {
        memberRoleList.value.forEach((item: any) => {
          if (element.memberRoleName == item.memberRoleName) {
            element.memberRoleId = item.id;
          }
        });
      });

      loading.value = true;
      const text = formData.id ? "编辑" : "新增";
      await request({
        url: "/mes/mescrew/save",
        method: "post",
        data: formData,
      }).finally(() => {
        loading.value = false;
      });
      ElMessage.success(text + `成功`);
      closeDialog();
      emit("reset-table", formData.id);
    }
  });
}
// 获取选中的数据进行回显并赋值
const noRepeat = ref(true);
function getDayPerson(Ids: string[], Objects: any, index) {
  for (let i = 0; i < formData.crewMembers.length; i++) {
    if (formData.crewMembers[i].memberId == Objects[0].id) {
      ElMessage.error("该班组成员已存在，请重新选择");
      noRepeat.value = false;
      break;
    }
  }

  if (noRepeat.value == true) {
    console.log(noRepeat.value);
    formData.crewMembers[index].memberList = Objects.map((item: any) => {
      return { id: item.id, personName: item.personName };
    });
    formData.crewMembers[index].memberEmpNo = Objects[0].empNo;
    formData.crewMembers[index].memberId = Objects[0].id;
    formData.crewMembers[index].memberName = Objects[0].personName;
    formData.crewMembers[index].sex = Objects[0].sex;
  } else {
    formData.crewMembers[index].memberList = [];
    noRepeat.value = true;
  }
}

const memberRoleList: any = ref([]);
const memberRole = async () => {
  await request({
    url: "mes/mesmemberrole/getList",
    method: "post",
    data: {
      enabled: 1,
    },
  }).then((res) => {
    memberRoleList.value = res.data;
  });
};
onMounted(() => {
  memberRole();
});
</script>
